package com.wowoai.admin.useroption.service.impl;

import com.wowoai.admin.useroption.repository.jpa.AdminUserOptionRepository;
import com.wowoai.common.basemodule.BusinessException;
import com.wowoai.common.enums.ResponseEnum;
import com.wowoai.common.userInfo.UserInfo;
import com.wowoai.user.entity.UserEntity;
import com.wowoai.user.repository.UserRepositoryI;
import com.wowoai.admin.useroption.controller.enums.AdminUserOptionEnum;
import com.wowoai.admin.useroption.entity.AdminUserOptionEntity;
import com.wowoai.admin.useroption.service.AdminUserOptionServiceI;
import com.wowoai.utils.IdGeneratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
public class AdminUserOptionServiceImpl implements AdminUserOptionServiceI {

    private final UserRepositoryI userRepositoryI;

    private final AdminUserOptionRepository adminUserOptionRepository;

    public AdminUserOptionServiceImpl(UserRepositoryI userRepositoryI, AdminUserOptionRepository adminUserOptionRepository){
        this.userRepositoryI = userRepositoryI;
        this.adminUserOptionRepository = adminUserOptionRepository;
    }

    @Transactional
    @Override
    public void permanentScore(UserInfo userInfo, Long optionUserId, Integer permanentScoreOpt) {
        UserEntity userEntity = userRepositoryI.findById(optionUserId);
        Integer permanentScore = userEntity.getPermanentScore();
        permanentScore += permanentScoreOpt;
        userEntity.setPermanentScore(permanentScore >= 0 ? permanentScore : 0);
        userEntity.setModifyTime(System.currentTimeMillis());
        userEntity.setModifierId(userInfo.getUserId());
        userEntity.setModifierName(userInfo.getUserName());
        userRepositoryI.update(userEntity);

        // 写入日志操作
        AdminUserOptionEntity userOptionEntity = AdminUserOptionEntity.create(IdGeneratorUtil.nextId(), userInfo.getUserId(), userInfo.getUserName());
        userOptionEntity.setType(AdminUserOptionEnum.PERMANENT_SCORE_OPTION.getType());
        userOptionEntity.setTypeName(AdminUserOptionEnum.PERMANENT_SCORE_OPTION.getTypeName());
        userOptionEntity.setOptionUserId(optionUserId);
        userOptionEntity.setOptionUserName(userEntity.getNickName());
        userOptionEntity.setPermanentScoreOpt(permanentScoreOpt);
        adminUserOptionRepository.save(userOptionEntity);
    }
}
